<template>
  <div class="app-container">

    <!--搜索表单-->
    <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
      <el-form-item label="院系">
        <el-input
          v-model="searchClazz.department"
          placeholder="请输入院系名称"
        />
      </el-form-item>
      <el-form-item label="专业">
        <el-input
          v-model="searchClazz.professional"
          placeholder="请输入专业名称"
        />
      </el-form-item>
      <el-form-item label="入学年份">
          <el-date-picker
              v-model="searchClazz.entry"
              type="year"
              value-format="yyyy"
              placeholder="请选择入学年份">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchClazz.status" placeholder="请选择">
          <el-option label="禁用" value="0" />
          <el-option label="正常" value="1" />
          <el-option label="毕业" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>

    <!--按钮-->
    <el-row>
      <el-button type="danger" size="medium" @click="deleteByIds">- 批量删除</el-button>
      <el-button type="primary" size="medium" @click="dialogVisible = true; emp = { image: ''};">+ 新增班级</el-button>
      <el-button type="primary" size="medium" @click="exportExcelFile" >导出表格</el-button>
      <el-button type="primary" size="medium" @click="importExcelFile" >导入表格</el-button>
      <input type="file" ref="excelFileInput" accept=".xls,.xlsx" style="display: none;" @change="handleExcelFileChange" />
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog ref="form" title="编辑班级" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="clazz" label-width="80px" size="mini">
        <el-form-item label="院系">
          <el-input v-model="clazz.department" />
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="clazz.professional" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="clazz.claz" />
        </el-form-item>
        <el-form-item label="班级人数">
          <el-input v-model="clazz.count" />
        </el-form-item>
        <el-form-item label="入学年份">
            <el-date-picker
                v-model="clazz.entry"
                type="year"
                value-format="yyyy"
                placeholder="选择入学年份">
            </el-date-picker>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="clazz.status" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="department" label="院系" align="center" />
        <el-table-column prop="professional" label="专业" align="center" />
        <el-table-column prop="claz" label="班级" align="center" />
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0" style="margin-right: 10px">禁用</span>
            <span v-if="scope.row.status === 1" style="margin-right: 10px">正常</span>
            <span v-if="scope.row.status === 2" style="margin-right: 10px">毕业</span>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="班级人数" align="center" />

        <el-table-column align="center" label="入学年份">
          <template slot-scope="scope">
            {{ scope.row.entry }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后操作时间">
          <template slot-scope="scope">
            {{ dayjs(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="searchClazz.pageNum"
      :limit.sync="searchClazz.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById, exportExcel, importExcel } from '@/api/clazz.js'
import {findAll} from '@/api/dept.js'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'

export default {
    data() {
        return {
            background: true,
            // 总记录数
            totalCount: 100,
            // 添加数据对话框是否展示的标记
            dialogVisible: false,
            // 模型数据
            searchClazz: {
                professional: '',
                department: '',
                entry: '',
                pageNum: 1,
                pageSize: 10,
            },
            emp: {
                image: ''
            },
            clazz: {
            },
            deptList: [],
            statusList: [{ id: 0, name: '禁用' }, { id: 1, name: '正常' }, { id: 2, name: '毕业' }],
            jobList: [
                {
                    id: 1,
                    name: '班主任'
                },
                {
                    id: 2,
                    name: '讲师'
                },
                {
                    id: 3,
                    name: '学工主管'
                },
                {
                    id: 4,
                    name: '教研主管'
                }
            ],

            // 被选中的id数组
            selectedIds: [],
            // 复选框选中数据集合
            multipleSelection: [],
            // 表格数据
            tableData: [],
            token: { token: getToken() }
        }
    },

    mounted() {
        this.page() // 当页面加载完成后，发送异步请求，获取数据
        findAll().then((result) => {
            this.deptList = result.data
        })
    },

    methods: {
        dayjs,
        // 查询分页数据
        page() {
            page(this.searchClazz).then((res) => {
                this.totalCount = res.total
                this.tableData = res.rows
            })
        },

        // 复选框选中后执行的方法
        handleSelectionChange(val) {
            this.multipleSelection = val
        },

        // 查询方法
        onSubmit() {
            this.searchClazz.pageNum = 1
            this.page()
        },

        clear() {
            this.searchClazz = { name: '', gender: '' }
            this.beginTime = '',
            this.endTime = ''
            this.entrydate = ''
            this.page()
        },
        // 添加数据
        add() {
            let operator

            if (this.clazz.id) {
                // 修改
                operator = update(this.clazz)
            } else {
                operator = add(this.clazz)
            }

            operator.then((resp) => {
                this.dialogVisible = false
                this.page()
                this.$message({ message: '恭喜你，保存成功', type: 'success' })
                this.clazz = { image: '' }
            })
        },
        update(id) {
            // 1. 打开窗口
            this.dialogVisible = true
            // 2. 发送请求

            selectById(id).then((result) => {
                this.clazz = result.data
                this.clazz
            })
        },

        // 分页
        handleSizeChange(val) {
            // 重新设置每页显示的条数
            this.searchClazz.pageSize = val
            this.page()
        },

        handleCurrentChange(val) {
            // 重新设置当前页码
            this.searchClazz.pageNum = val
            this.page()
        },

        // 删除员工信息
        deleteById(id) {
            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 2. 发送AJAX请求
                deleteById(id).then((resp) => {
                    // 删除成功
                    this.$message.success('恭喜你，删除成功')
                    this.page()
                })
            }).catch(() => {
                // 用户点击取消按钮
                this.$message.info('已取消删除')
            })
        },

        // 批量删除员工信息
        deleteByIds() {
            // 弹出确认提示框
            this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 用户点击确认按钮
                // 1. 创建id数组, 从 this.multipleSelection 获取即可
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    this.selectedIds[i] = this.multipleSelection[i].id
                }

                // 2. 发送AJAX请求
                deleteById(this.selectedIds).then((resp) => {
                    // 删除成功
                    this.$message.success('恭喜你，删除成功')
                    this.page()
                })
            }).catch(() => {
                // 用户点击取消按钮
                this.$message.info('已取消删除')
            })
        },

      exportExcelFile() {
          exportExcel().then(response => {
            const blob = new Blob(
              [response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = '班级数据.xlsx';
            link.click();
            window.URL.revokeObjectURL(url);
          }).catch(error => {
            this.$message.error('导出失败：' + (error.response?.data?.msg || '网络错误'));
          });

      },
      // 导入Excel文件
      importExcelFile() {
        this.$refs.excelFileInput.click();
      },

      // 处理选择的Excel文件
      handleExcelFileChange(e) {
        const file = e.target.files[0];
        if (!file) return;
        // 验证文件类型
        const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        if (!validTypes.includes(file.type)) {
          this.$message.error('请上传Excel文件（.xls或.xlsx）');
          return;
        }
        // 创建FormData并上传
        const formData = new FormData();
        formData.append('file', file);
        importExcel(formData).then(res => {
          if (res.data.code == '200') {
            this.$message.success('班级数据导入成功');
            this.page(); // 刷新表格数据
          } else {
            this.$message.error(res.data.msg || '导入失败，请检查文件内容');
          }
          // 清空文件输入
          this.$refs.excelFileInput.value = '';
        }).catch(err => {
          this.$message.error('网络错误，导入失败');
        });
      },
    }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
